package com.cndongtai.map;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class GDMapServer {
	
	private static final String ENCODEING = "utf-8";
	private static final int CONNECT_TIMEOUT = 1000*1;
	private static final int SEND_TIMEOUT =1000*1;
	
	private static final String URL = "http://restapi.amap.com/v3/geocode/geo";
	private static final String RE_URL = "http://restapi.amap.com/v3/geocode/regeo";
	private static final String TRANSFER_URL = "http://restapi.amap.com/v3/assistant/coordinate/convert";
	private static final String KEY = "2862fa4efe27fe10dab8bccf13c8aca9";

	public String[] locationTransfer(String lng, String lat) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("key", KEY);
		params.put("locations", lng+","+lat);
		params.put("coordsys", "gps");
		params.put("output", "JSON");
		
		String rspContent = doPost(TRANSFER_URL, params);
		System.out.println("rspContent==>"+rspContent);
		
		String[] result = new String[2];
		if(rspContent==null || "".equals(rspContent)) {
			return null;
		}
		
		JSONObject json = JSONObject.fromObject(rspContent);
		String status = (String) json.get("status");
		if("1".equals(status)) {
			String resultJson = json.getString("locations");
			
			if(resultJson==null || "".equals(resultJson)) {
				return null;
			}
			
			String[] locationArr = resultJson.split(",");
			if(locationArr.length==2) {
				result[0] = locationArr[0];
				result[1] = locationArr[1];
				
				return result;
			}
		}
		System.out.println("rspContent==>"+rspContent);
		return null;
	}
	
	public String queryAddressByLatAndLng(String lat, String lng) {
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("key", KEY);
		params.put("location", lng+","+lat);
		params.put("radius", "1000");
		params.put("extensions", "all");
		params.put("batch", "false");
		params.put("roadlevel", "0");
		
		String rspContent = doPost(RE_URL, params);
		System.out.println("rspContent==>"+rspContent);
		
		if(rspContent==null || "".equals(rspContent)) {
			return "";
		}
		
		JSONObject json = JSONObject.fromObject(rspContent);
		String status = (String) json.get("status");
		if("1".equals(status)) {
			JSONObject result = json.getJSONObject("regeocode");
			if(result!=null) {
				Object formatted_addres = result.get("formatted_address");
				if(formatted_addres instanceof JSONArray) {
					return "";
				}
				
				if(formatted_addres!=null) {
					return formatted_addres.toString();
				}
			}
		}
		
		return "";
	}
	
	public String[] queryLatAndLngByAddress(String addressName) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("address", addressName);
		params.put("output", "JSON");
		params.put("key", KEY);
		
		String rspContent = doPost(URL, params);
		System.out.println("rspContent==>"+rspContent);
		
		String[] result = new String[2];
		if(rspContent==null || "".equals(rspContent)) {
			return null;
		}
		
		JSONObject json = JSONObject.fromObject(rspContent);
		String status = (String) json.get("status");
		if("1".equals(status)) {
			JSONArray resultJson = json.getJSONArray("geocodes");
			
			if(resultJson==null || resultJson.size()==0) {
				return null;
			}
			
			String location = resultJson.getJSONObject(0).getString("location");
			if(location!=null && !"".equals(location)) {
				String[] locationArr = location.split(",");
				if(locationArr.length==2) {
					result[0] = locationArr[0];
					result[1] = locationArr[1];
					
					return result;
				}
			}
		}
		System.out.println("rspContent==>"+rspContent);
		return null;
	}
	
	private String doPost(String reqUrl, Map<String, String> parameters) {
		HttpURLConnection url_con = null;
		StringBuffer responseContent = new StringBuffer();
		
		try {
			StringBuffer params = new StringBuffer();
			for (Iterator<?> iter = parameters.entrySet().iterator(); iter.hasNext();) {
				Entry<?, ?> element = (Entry<?, ?>) iter.next();
				params.append(element.getKey().toString());
				params.append("=");
				params.append(URLEncoder.encode(element.getValue().toString(), ENCODEING));
				params.append("&");
			}

			if (params.length() > 0) {
				params = params.deleteCharAt(params.length() - 1);
			}
			
			URL url = new URL(reqUrl);
			url_con = (HttpURLConnection) url.openConnection();
			url_con.setRequestMethod("GET");
			url_con.setConnectTimeout(CONNECT_TIMEOUT);
			url_con.setReadTimeout(SEND_TIMEOUT);
			url_con.setDoOutput(true);
			byte[] b = params.toString().getBytes();
			url_con.getOutputStream().write(b, 0, b.length);
			url_con.getOutputStream().flush();
			url_con.getOutputStream().close();

			InputStream in = url_con.getInputStream();
			
			byte[] echo = new byte[10 * 1024];
			int len = 0;
			while((len = in.read(echo)) > 0) {
				responseContent.append((new String(echo, 0, len, ENCODEING)).trim());
			}
			
			int code = url_con.getResponseCode();
			if (code != 200) {
				responseContent.append("ERROR" + code);
			}
		}catch (IOException e) {
			System.out.println("网络故障:"+ e.toString());
		}finally {
			if (url_con != null) {
				url_con.disconnect();
			}
		}
		return responseContent.toString();
	}
}
